-- remote_magic
-- created by xinj
-- 每若干轮自动攻击

return {
    apply = function(prop, baseValue)
        return prop[3];
    end,

    -- 每回合触发
    trigger = function(who, prop, arg)
        -- 有无敌状态
        if #PropM.fetchProps(ME.user, "invincible") > 0 then
            return false;
        end

        -- 是不是攻击的回合
        local step = tonumber(prop[2]);
        local round = CombatM.getRound();
        local startRound;
        local grid;

        if who.type == OBJECT_TYPE_MONSTER then
            grid = DungeonM.getGridByPos(who:getPos());
            startRound = grid.openRound or 0;
        else
            startRound = 0;
        end

        if (round - startRound) % step ~= 0 then
            return false;
        end

        if round <= startRound then
            return false;
        end

        local action = who.action or 0;
        if round <= action then
            return false;
        end

        local target;
        local skillId = prop[3];
        local skills = SkillM.getSkillTable();
        if not skills[skillId] then
            return false;
        end

        local dbase = SkillM.query(skillId, "dbase") or {};

        -- 目标
        if SkillM.needTarget(skillId) then
            target = ME.user;
        -- 召唤技能目标为自己
        elseif dbase["is_summon"] == 1 then
            target = who;
        else
            for p = 1, DUNGEON_WIDTH * DUNGEON_HEIGHT do
                grid = DungeonM.getGridByPos(p);

                -- 是未死亡的怪物
                if grid:isOpened() and
                    grid:isMonster() and
                    not grid.monster:isDead() and
                    grid.monster ~= who then
                    target = grid.monster;
                    break;
                end
            end

            -- 已经没有目标了，不处理
            if not target then
                return false;
            end
        end

        -- 记录最经一次行动
        who.action = round;

        local msg = string.format("%s远程魔法，hit_by_user = %s", who:query("name") or "", who.dbase:query("hit_by_user", 0));
        trace("remote_magic", msg);
        -- 初始化序列
        SkillM.initSequence(who, who, 0);
        -- 远程怪攻击动作
        SkillM.getSequence(who):remoteAttack(who, arg, skillId);
        SkillM.apply(who, target, skillId, CombatM.getRound());
        if target == ME.user then
            SkillM.getSequence(arg):start(who, arg, 0);
        end
        --EventMgr.fire(event.PLAYER_MOVE, who:getOwner());

        return true;
    end,

    clear = function(who, prop)
        -- 同步清除掉改变技能间隔的属性
        PropM.deletePropById(who, "special", "add_cd");
    end,

    record = function(target, prop, path)
        return false;
    end
};
